﻿
using System;
using System.IO;
using System.Xml.Serialization;
namespace DZParallelLib.Utility
{
    /// <summary>
    /// Helper classes for dealing with a deep zoom image.
    /// </summary>
    class DZImageIO
    {
        /// <summary>
        /// Load up a deepzoom image from the images that are specified in the DZ file. Will load into an image
        /// that has the square size of tile size or bigger.
        /// </summary>
        /// <param name="imageDZPath"></param>
        /// <param name="TileSize"></param>
        /// <remarks>
        /// This method won't do any rescalling - it will, but it will return something at least as big as long as
        /// that is possible.
        /// </remarks>
        internal static void Load(System.IO.FileInfo imageDZPath, uint TileSize)
        {
            // Load image info.

            var imageDescriptor = LoadImageDZFile(imageDZPath);

            // Get the proper level to fetch this guy into
            double maxDimension = Math.Max(imageDescriptor.Size.Height, imageDescriptor.Size.Width);
            var bestScale = TileSize / maxDimension;
            if (bestScale > 1.0)
                bestScale = 1.0;

            var level = Math.Floor(Math.Log10(bestScale) / Math.Log10(0.5));
        }

        /// <summary>
        /// Serialization services for the image that is coming in.
        /// </summary>
        static private XmlSerializer _imageDescriptorSerialization = new XmlSerializer(typeof(DZParallelLib.Data.Image));

        /// <summary>
        /// Load the data for the descriptor file.
        /// </summary>
        /// <param name="imageDZPath"></param>
        /// <returns></returns>
        internal static DZParallelLib.Data.Image LoadImageDZFile(FileInfo imageDZPath)
        {
            if (!imageDZPath.Exists)
                throw new FileNotFoundException(string.Format("image DZ xml ('{0}') file not found", imageDZPath.FullName));

            using (var rdr = imageDZPath.OpenRead())
            {
                return _imageDescriptorSerialization.Deserialize(rdr) as DZParallelLib.Data.Image;
            }
        }
    }
}
